package dev.entao.travel

import dev.entao.base.Name
import dev.entao.core.*
import dev.entao.core.render.sendBack
import dev.entao.core.render.sendSuccess
import dev.entao.core.slices.SessionSlice
import dev.entao.log.logd
import dev.entao.page.bs.LoginPage
import dev.entao.sql.EQ
import dev.entao.travel.admin.AccountPages
import dev.entao.travel.model.Account

@Controller(index = true)
class IndexPage(context: HttpContext) : AdminPages(context) {

    @Action
    fun area() {
        val ls = AreaStorage.provinceList
        for (p in ls) {
            logd(p)
        }
        logd("------")
        val cl = AreaStorage.citiesOfProvince("310000")
        for (c in cl) {
            logd(c)
        }
        logd("-------")
        val aa = AreaStorage.countryOfCity("310101")
        for (a in aa) {
            logd(a)
        }
        sendSuccess()
    }

    @Action(index = true)
    fun index() {
        val aid = SessionSlice.getAccountId(context)
        if (aid == null) {
            context.redirect(::login.uri)
            return
        }
        context.redirect(AccountPages::list.uri)
    }

    @Action
    @LoginWebAction
    fun login() {
        LoginPage(context).apply {
            fromAction(::loginResult)
        }.send()
    }

    @Action
    fun loginResult(@Name("phone") user: String, pwd: String) {
        val ac = Account.one(Account::phone EQ user, Account::pwd EQ pwd)
        if (ac != null) {
            SessionSlice.putAccountId(context, ac.id, AppConst.ACCOUNT)
            context.redirect(AccountPages::list.uri)
        } else {
            sendBack {
                setError("用户名或密码错误")
            }
        }
    }

}